package com.sskj.gocoinapp.ui.activity;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.widget.FrameLayout;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.m.bean.AppVersionBean;
import com.sskj.gocoin.v.fragment.AppUpDateFragment;
import com.sskj.gocoinapp.R;
import com.sskj.gocoinapp.component.DaggerUserDataComponent;
import com.sskj.gocoinapp.presenter.MainActivityPresenter;
import com.sskj.level.bean.GonggaoBean;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.MainTabChange;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

@Route(path = RConfig.APP_MAIN)
public class MainActivity extends BaseActivity<MainActivityPresenter> {
    @BindView(R.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private int curPos = 0;
    private ArrayList<Fragment> fragments;
    HashMap<Integer, Fragment> tabMap = new HashMap<>();
    private MaterialDialog gongGaoTip;

//    @Override
//    public boolean getImmersion() {
////        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
////            //透明状态栏
////            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
////            //透明导航栏
////            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
////        }
//
//        return true;
//    }

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_main;
    }

    @Override
    public MainActivityPresenter getPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected void dealFirstSaveInstance(Bundle savedInstanceState) {
        FragmentManager mManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            List<Fragment> fragments = mManager.getFragments();
            FragmentTransaction fragmentTransaction = mManager.beginTransaction();
            for (int i = 0; i < fragments.size(); i++) {
                fragmentTransaction.remove(fragments.get(i));
            }
            fragmentTransaction.commitAllowingStateLoss();
        }
    }


    @Override
    protected void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });

        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity1), R.mipmap.lib_hangqing, R.mipmap.lib_hangqing_hover));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity2), R.mipmap.lib_zixun, R.mipmap.lib_zixun_hover));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity3), R.mipmap.lib_heyue, R.mipmap.lib_heyue_hover));
//        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity4), R.mipmap.lib_fabi, R.mipmap.lib_fabi_hover));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity5), R.mipmap.lib_wd, R.mipmap.lib_wd_hover));
        commonTabLayout.setTabData(tabItems);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position >= 3 && userData == null) {
                    showLogin();
                } else {
                    changeTab(position);
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_HANGQING).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_ZIXUN).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_MAIN).withString(Constans.CODE, "btc_usdt").navigation());
//        fragments.add((Fragment) ARouter.getInstance().build(RConfig.FABI_FRAGMENT).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.MINE_FRAGMENT_MAIN).navigation());

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayout, fragments.get(2))
                .add(R.id.frameLayout, fragments.get(0))
                .hide(fragments.get(2))
                .show(fragments.get(0))
                .commitAllowingStateLoss();
        tabMap.put(0, fragments.get(0));
        tabMap.put(2, fragments.get(2));

    }

    private void changeTab(int position) {
        if (tabMap.get(position) == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.frameLayout, fragments.get(position))
                    .hide(fragments.get(curPos))
                    .show(fragments.get(position))
                    .commitAllowingStateLoss();
            tabMap.put(position, fragments.get(position));
        } else {
            getSupportFragmentManager()
                    .beginTransaction()
                    .hide(fragments.get(curPos))
                    .show(fragments.get(position))
                    .commitAllowingStateLoss();
        }
        RxBus.getDefault().post(new MainTabChange(position));
        curPos = position;
    }

    @Override
    protected void initData() {
        mPresenter.initWebSocket();
        mPresenter.getGonggao();
        mPresenter.getNewVersion();
    }

    private void showLogin() {

        commonTabLayout.setCurrentTab(curPos);
        ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
        overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
    }

    @Subscribe(code = RxBusCode.MINING_LEVEL, threadMode = ThreadMode.MAIN)
    public void changePage() {
        commonTabLayout.setCurrentTab(2);
        changeTab(2);
    }

    @Subscribe(code = RxBusCode.CHANGE_ZIXUN, threadMode = ThreadMode.MAIN)
    public void changeZixun() {
        commonTabLayout.setCurrentTab(1);
        changeTab(1);
    }

    public void showGonggao(GonggaoBean data) {
        if (!TextUtils.isEmpty(data.getValue().trim())) {
            TipUtil.showGonggao(this, data.getValue());
        }
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }


        String verName = APKVersionCodeUtils.getVerName(this);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);

        if (APKVersionCodeUtils.compareVersion(versionBean.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            appUpDateFragment.show(fragmentTransaction, "update");
        }
    }

    @Subscribe(code = RxBusCode.LOGOUT, threadMode = ThreadMode.MAIN)
    public void changeHangQing() {
        commonTabLayout.setCurrentTab(0);
        changeTab(0);
    }

}
